package com.luo.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.luo.model.Summary;
import com.luo.model.SummaryInfoVO;
import com.luo.service.SummaryService;
import lombok.SneakyThrows;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;

/**
 * 功能：
 * 作者：Luo。
 * 日期：2024/3/26 11:15
 */
@WebServlet("/pay/aliPay")
public class AliPay extends HttpServlet {

	SummaryService summaryService = new SummaryService();

	@SneakyThrows
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 获取参数
		String orderId = req.getParameter("orderId");
		String redirect = req.getParameter("redirect");

		// 配置支付宝个人参数
		AlipayClient alipayClient = new DefaultAlipayClient(
				"https://openapi-sandbox.dl.alipaydev.com/gateway.do",
				"9021000134679165",
				"MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQCGrRVjIhvgIIS5I13G5TfA9H8plwYIUifSzSQALUmDThQTl66ahgesfegjkjEx6iynD9LLN6X/hDJ7a5Z1lNpyoRBM+jvxiIrZSSRLhpFUgCuMuizNENkeLIKEv1J0tuvoicEFfrKQu4oXpa+Oxe30l6rldeBwZodWhm5Fe+DeLrB4PitGc/lYQc70UtGYodczCEvHS85q5Qex2U5KPC9WCJhkDtCiFHxLg/vfAmcRugCD4N6gpMiUR8P2dDuGq2Uw1BSXCyCWU9N0XI/OnJTCsH0hKz5SEaM/3Oxx4VwjqJ9zs8Gsi6ogvBlDL1xIqjEDuRoTr7ULA2QQ3vI5QgRHAgMBAAECggEBA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XCN/H3mTyYzvgrf0zYYZBR+0AmuLAsVr4YufEFvinN8Y1mTja+ABFu3VlCJgMqh2CYXRPPB3TKguvJpk1lJwzJ9UCGMy44TkrUkH8W+qD80+pnVRIY1nDozwl/NyBGJYD0MYZWBg5ujJMcJMTdvVBg==",
				"json",
				"utf8",
				"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAg7QT3aGVq8B2DcT+B1nkI1IVW2ML211nhy5pCk9IdkC+jBLuPwpUS6HjPOuyuaFB6Uf/Ia/EYpLFui69TxQhzcJY4R3p8U/B8eXwSm03ZrBMo6HcIa+NIYz6i4YnFJy1ynfNOu5nKvBXIeCEMU+Zb4j8IpXIDCrFgUVV9vIpiCg86v0KFo29UBtn+tYswsMQWCllZ0OoFwA8chl2Sy+k/xJv+ouPBUWf/f5z4Ah24DjC7+J+sLHTro7qIpdG9UFA9rB+KNPbpQSj4paKajMHzo2wP8FOUujjTe6od0Y5QJSFq3Sj7gS7GbWvzyaZKMK4A6b3W1LL/42i1nO+94BzmQIDAQAB",
				"RSA2");
		AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();

		/******必传参数******/
		//根据订单号查询所需参数
		Summary summary = summaryService.querySummaryById(orderId);
		if ("2".equals(summary.getStatus())) {
			// 订单超时逻辑

			return;
		} else if ("1".equals(summary.getStatus())) {
			// 订单支付完成逻辑

			return;
		}
		// 计算订单金额
		SummaryInfoVO summaryInfo = summaryService.getSummaryInfo(summary);
		JSONObject bizContent = new JSONObject();
		//商户订单号，商家自定义，保持唯一性
		bizContent.put("out_trade_no", orderId);
		//支付金额，最小值0.01元
		bizContent.put("total_amount", summaryInfo.getMoneyCount());
		//订单标题，不可使用特殊符号
		bizContent.put("subject", summaryInfo.getGoodsNames());
		//电脑网站支付场景固定传值FAST_INSTANT_TRADE_PAY
		bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");

		/******可选参数******/
		//bizContent.put("time_expire", "2022-08-01 22:00:00");

		//// 商品明细信息，按需传入
		//JSONArray goodsDetail = new JSONArray();
		//JSONObject goods1 = new JSONObject();
		//goods1.put("goods_id", "goodsNo1");
		//goods1.put("goods_name", "子商品1");
		//goods1.put("quantity", 1);
		//goods1.put("price", 0.01);
		//goodsDetail.add(goods1);
		//bizContent.put("goods_detail", goodsDetail);

		//异步接收地址，仅支持http/https，公网可访问
		// request.setNotifyUrl("http://127.0.0.1:8080/mall_war_exploded/submitSummarySuccess?id=" + orderId + "&money=" + summaryInfo.getMoneyCount());
		request.setNotifyUrl("http://237282go74.vicp.fun/mall_war_exploded/submitSummarySuccess?id=" + orderId + "&money=" + summaryInfo.getMoneyCount());
		//同步跳转地址，仅支持http/https
		request.setReturnUrl(redirect + "?id=" + orderId);

		// 扩展信息，按需传入
		JSONObject extendParams = new JSONObject();
		// extendParams.put("sys_service_provider_id", "2088511833207846");
		extendParams.put("qr_pay_mode", 2);
		bizContent.put("extend_params", extendParams);

		request.setBizContent(bizContent.toString());
		AlipayTradePagePayResponse response = alipayClient.pageExecute(request, "POST");
		// 如果需要返回GET请求，请使用
		// AlipayTradePagePayResponse response = alipayClient.pageExecute(request,"GET");
		String pageRedirectionData = response.getBody();
		System.out.println(pageRedirectionData);

		if (response.isSuccess()) {
			resp.setContentType("text/html");
			resp.getWriter().write(pageRedirectionData);
			resp.getWriter().close();
		} else {
			System.out.println("调用失败");
		}
	}
}
